<template>
  <!-- <div>这是一个编辑资料页面</div> -->
  <div>
    <div>
      <!-- 导航栏 -->
      <van-nav-bar
        class="page-nav-bar"
        left-arrow
        title="个人信息"
        @click-left="$router.push({ path: '/my' })"
      >
      </van-nav-bar>
      <!-- /导航栏 -->
    </div>
    <div class="celldiv">
      <van-cell center title="头像" is-link>
        <template>
          <van-image round class="userphoto" :src="userinfo.photo" />
        </template>
        <!-- 图片上传 -->
        <!--方法1
           <van-uploader :after-read="afterRead" :max-count="1" ref="file">
          <van-image round class="userphoto" :src="userinfo.photo"></van-image>
        </van-uploader> -->
      </van-cell>
      <input
        type="file"
        class="userphotoimg"
        @change="optionImg"
        ref="userphoto"
      />
      <van-cell
        title="昵称"
        :value="userinfo.name"
        is-link
        @click="editNameShowFn"
      />
      <van-cell
        :value="userinfo.gender == 0 ? '男' : '女'"
        title="性别"
        is-link
        @click="editGenderShowFn"
      />
      <van-cell
        :value="userinfo.birthday"
        title="生日"
        is-link
        @click="editBirthdayShowFn"
      />
    </div>
    <!-- 修改昵称弹层  -->
    <van-popup
      v-model="editNameShow"
      class="vanpopup"
      position="bottom"
      style="height: 100%"
    >
      <van-nav-bar
        title="设置昵称"
        left-text="取消"
        right-text="完成"
        @click-right="editNameFn"
        @click-left="editNameShow = false"
      >
      </van-nav-bar>
      <div class="popupname">
        <van-field
          v-model="namemessage"
          rows="2"
          autosize
          type="textarea"
          maxlength="7"
          placeholder="请输入昵称"
          show-word-limit
        ></van-field>
      </div>
    </van-popup>
    <!-- 修改性别弹层 -->
    <van-popup v-model="editGenderShow" class="vanpopup" position="bottom">
      <van-picker
        title="性别"
        show-toolbar
        :columns="columns"
        :default-index="userinfo.gender"
        @confirm="editGenderFn"
        @cancel="editGenderShow = false"
      />
    </van-popup>
    <!-- 修改生日 -->
    <van-popup v-model="editBirthdayShow" class="vanpopup" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="editBirthdayShow = false"
        @confirm="editBirthdayFn"
      />
    </van-popup>
    <!-- 修改图片弹层 -->
    <van-popup
      v-model="editPhotoShow"
      style="height: 100%"
      class="vanpopup"
      position="bottom"
    >
      <!-- 放置我们选择的图片 -->
      <div class="imgbg" v-if="editPhotoShow">
        <img
          :src="yulanPhotoSrc"
          alt=""
          class="imgbgphoto"
          ref="yulanPhotoDom"
        />
        <div class="toolbar">
          <div class="cancel" @click="editPhotoShow = false">取消</div>
          <div class="confirm" @click="onConfirmPhoto">完成</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<script>
import {
  getUserPrpfileApi,
  updataUserPhotoApi,
  updataUserProfileApi,
} from "@/api/user";
import moment from "moment";
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
export default {
  data() {
    return {
      editNameShow: false, //昵称弹层
      editGenderShow: false, //判断性别弹层
      editBirthdayShow: false, //生日
      editPhotoShow: false, //编辑头像弹层
      namemessage: "",
      userinfo: {},
      columns: ["男", "女"],
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(), //现在的日期
      fileList: [{ url: "" }],
      yulanPhotoSrc: "",
      cropper: "",
    };
  },
  async created() {
    try {
      let { data } = await getUserPrpfileApi();
      this.userinfo = data.data;
    } catch (error) {
      console.log(error);
    }
  },
  methods: {
    editNameShowFn() {
      this.editNameShow = true;
      this.namemessage = this.userinfo.name;
    },
    async editNameFn() {
      console.log("完成");
      try {
        this.$toast.loading({
          message: "更新中....",
        });
        let obj = {
          name: this.namemessage,
        };
        await updataUserProfileApi(obj);
        this.$toast.success("更新成功");
        this.editNameShow = false;
        this.userinfo.name = this.namemessage;
      } catch (error) {
        this.$toast.fail("昵称更新失败，请重试...");
        console.log(error);
      }
    },
    editGenderShowFn() {
      this.editGenderShow = true;
    },
    async editGenderFn(item, index) {
      try {
        this.$toast.loading({
          message: "更新中....",
        });
        let obj = {
          gender: index,
        };
        await updataUserProfileApi(obj);
        this.$toast.success("更新成功");
        this.editGenderShow = false;
        //修改完成后 页面性别没变化
        this.userinfo.gender = index;
      } catch (error) {
        this.$toast.fail("昵称更新失败，请重试...");
        console.log(error);
      }
    },
    editBirthdayShowFn() {
      this.editBirthdayShow = true;
    },
    async editBirthdayFn() {
      let data = moment(this.currentDate).format("YYYY-MM-DD");
      try {
        this.$toast.loading({
          message: "更新中....",
        });
        let obj = {
          birthday: data,
        };
        await updataUserProfileApi(obj);
        this.$toast.success("更新成功");
        this.editBirthdayShow = false;
        //修改视图
        this.userinfo.birthday = data;
      } catch (error) {
        this.$toast.fail("昵称更新失败，请重试...");
        console.log(error);
      }
    },
    // async afterRead(file) {
    //   // 此时可以自行将文件上传至服务器

    //   let forms = new FormData();
    //   forms.append("photo", file.file);
    //   console.log(forms);
    //   try {
    //     await updataUserPhotoApi(forms);
    //     this.userinfo.photo = file.content;
    //   } catch (error) {
    //     console.log(error);
    //   }
    // },
    optionImg() {
      let obj = this.$refs.userphoto.files[0];
      console.log("图片对象" + obj);
      let imgsrc = window.URL.createObjectURL(obj);
      this.yulanPhotoSrc = imgsrc;
      console.log("图片地址" + imgsrc);

      this.editPhotoShow = true;
      //VUE的核心概念 dom 的更新是异步的  所以使用 nexttick 来解决
      this.$nextTick(() => {
        let image = this.$refs.yulanPhotoDom;
        console.log(image);
        this.cropper = new Cropper(image, {
          aspectRatio: 16 / 9,
          crop(event) {
            console.log(event.detail.x);
            console.log(event.detail.y);
            console.log(event.detail.width);
            console.log(event.detail.height);
            console.log(event.detail.rotate);
            console.log(event.detail.scaleX);
            console.log(event.detail.scaleY);
          },
        });
      });
    },
    onConfirmPhoto() {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        const formdata = new FormData();
        formdata.append("photo", blob);
        try {
          this.$toast.loading({
            message: "更新中....",
          });
          let { data } = await updataUserPhotoApi(formdata);
          this.$toast.success("更新成功");
          this.userinfo.photo = data.data.photo;
          this.editPhotoShow = false;
        } catch (error) {
          this.$toast.fail("更新失败");
          console.log(error);
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.vanpopup {
  background-color: #f5f7f9;
  .popupname {
    padding: 20px;
  }
}
.userphoto {
  width: 60px;
  height: 60px;
}
.celldiv {
  position: relative;
  .userphotoimg {
    position: absolute;
    top: 0px;
    left: 0px;
    right: 0px;
    opacity: 0;
    height: 100px;
  }
}
.imgbg {
  width: 100%;
  height: 100%;
  background: #000;
  .imgbgphoto {
    display: block;
    max-width: 100%;
  }
}
/deep/ .van-icon-arrow-left {
  color: #fff;
}
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  .cancel,
  .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
